package com.study.crypto.basic.service;

import com.study.crypto.basic.common.GeneralService;
import com.study.crypto.basic.config.CustomProperties;
import com.study.crypto.basic.entity.Certification;
import com.study.crypto.basic.mapper.CertificationMapper;
import com.study.crypto.basic.utils.EssPdfUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @author Songjin
 * @since 2021-02-21 23:02
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class CertificationService extends GeneralService<Certification> {

    @Autowired
    private CustomProperties properties;
    @Autowired
    private CertificationMapper certMapper;

    @Transactional(readOnly = true)
    public String selectMaxSerialNumber(String certType) {
        String defaultSerial;
        if (Certification.CERT_TYPE_SM2.equals(certType)) {
            defaultSerial = properties.getDefaultSerialNumberSm2();
        } else {
            defaultSerial = properties.getDefaultSerialNumberRsa();
        }
        return Optional.ofNullable(certMapper.selectMaxSerialNumber(certType))
                       .orElse(defaultSerial);
    }

    public boolean insertCertificates(List<Certification> certs) {
        Assert.notEmpty(certs, "传入证书为空");
        certs.forEach(cert -> {
            cert.setId(EssPdfUtil.genRandomUuid());
            cert.setCreateTime(LocalDateTime.now());
            cert.setUpdateTime(LocalDateTime.now());
            certMapper.insert(cert);
        });
        return true;
    }
    
}
